package com.android.chat.example;

import java.util.ArrayList;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.android.chat.connection.ServerConnect;
import com.android.chat.connection.SuggestServer;

public class ChatActivity extends Activity {
	public static final String CHAT_ID_KEY = "ChatID";
	
	private String currChatID;
	private EditText txtContent;
	private Connection conn;
	
	private ArrayList<String> messages;
	private ListView list;
	private Handler handler = new Handler();
	
	private String myName;
	private String buddyName;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.chat_layout);
		
		if (savedInstanceState != null) {
			currChatID = savedInstanceState.getString(CHAT_ID_KEY);
		} else {
			Bundle bundle = getIntent().getExtras();
			currChatID = bundle != null ? bundle.getString(CHAT_ID_KEY) : "";
			buddyName = bundle != null ? bundle.getString("CHAT_BUDDY") : "";
		}

		messages = new ArrayList<String>();
		
		conn = ServerConnect.getConnection();
		myName = conn.getAccountManager().getAccountAttribute("name");
		

		txtContent = (EditText) findViewById(R.id.txtContent);
		
		list = (ListView) findViewById(R.id.listChat);
		
		setListAdapter();

		Button btnSend = (Button) findViewById(R.id.btnSend);

		btnSend.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String content = txtContent.getText().toString();
				sendChatMessage(currChatID, content);
				txtContent.setText("");
			}
		});
		
		setConnection((XMPPConnection) conn);
	}

	private void setListAdapter() {
        ArrayAdapter<String> adapter = new ArrayAdapter<String>
            (this, R.layout.chat_row, messages);
        list.setAdapter(adapter);
        list.setSelectionFromTop(messages.size(), 0);
    }
	
	private void sendChatMessage(String id, String msg) {
		try {
			// Start a new conversation
			Chat chat = conn.getChatManager().createChat(id,
					new MessageListener() {

						public void processMessage(Chat chat, Message message) {
							// Print out any messages we get back to standard
							// out.
							System.out.println("Received message: " + message);
						}
					});
			chat.sendMessage(msg);
			
			messages.add(myName + ": " + msg);
			
			String suggest = SuggestServer.suggest(msg);
			if (suggest != null) {
				messages.add("Server sugguest: " + suggest);
			}
			
			setListAdapter();
		} catch (XMPPException e) {
			e.printStackTrace();
		}
	}
	
	public void setConnection (XMPPConnection connection) {
        this.conn = connection;
        
        if (connection != null) {
            //Packet listener to get messages sent to logged in user
            PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
            connection.addPacketListener(new PacketListener() {
                public void processPacket(Packet packet) {
                    Message message = (Message) packet;
                    if (message.getBody() != null) {
                    	
                        //String fromName = message.getFrom();
                        messages.add(buddyName + ": " + message.getBody());
                        handler.post(new Runnable(){
                            public void run() {
                                setListAdapter();
                            }
                        });
                    }
                }
            }, filter);
        }
    }
}
